package puyu.manage.service.common.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import puyu.manage.BackServiceApplication;
import puyu.manage.service.common.dao.CommonMapper;
import puyu.manage.service.common.service.CommonServiceI;
import puyu.manage.service.file.entity.SysTFileUpload;
import puyu.manage.service.file.entity.vo.FileUploadVo;
import puyu.manage.service.file.service.SysTFileCenterService;
import puyu.manage.service.file.service.SysTFileUploadService;
import puyu.manage.service.sample.dao.SampleDao;
import puyu.manage.service.source.dao.SysTSourceListMapper;
import puyu.manage.service.source.dao.SysTSourceMapper;
import puyu.manage.service.source.service.SysTSourceServiceImpl;
import puyu.manage.service.utils.CommonUtil;
import puyu.manage.service.utils.MessageUtils;
import puyu.manage.service.utils.StringUtils;
import puyu.manage.service.utils.except.BaseException;
import puyu.manage.service.utils.http.HttpClientUilt;
import puyu.manage.service.utils.redis.RedisUtil;
import puyu.manage.service.utils.tree.Zone;
import puyu.manage.service.utils.tree.ZoneUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class CommonServiceIImpl implements CommonServiceI {

    @Autowired(required = false)
    CommonMapper commonMapper;

    @Autowired(required = false)
    private RedisUtil redisUtil;
    @Resource
    private SysTFileUploadService sysTFileUploadService;

    @Resource
    private SysTFileCenterService sysTFileCenterService;

    @Resource
    private SysTSourceListMapper sysTSourceListMapper;

    @Resource
    private SampleDao sampleDao;
    @Override
    public List<Map<String, Object>> getElementTree(String elementcode, String elefilter)throws Exception {
        //
        List resList = new ArrayList<>();
        List<Map<String, Object>> eleDsList =  commonMapper.getEleDataSource(elementcode);
        if(eleDsList.isEmpty()) throw new Exception("未找到该数据字典");
        String datasource = eleDsList.get(0).get("datasource")+"";
        String sourceType = eleDsList.get(0).get("sourcetype")+"";
        String sql = "";
        if (StringUtils.isEmpty(elefilter))elefilter=" 1=1 ";
        if("1".equals(sourceType)){ //从sys_t_source_list码表里取
            resList = commonMapper.getBySourceCode(elementcode,elefilter);
        }else if ("2".equals(sourceType)){//SQL语句
            sql = "select  t.*  from("+datasource+") t where "+elefilter;
            resList =commonMapper.selectZoneTree(sql) ;
        }else {
            resList = commonMapper.getBySourceCode(elementcode,elefilter);
        }
        List treeList = ZoneUtils.buildTree(resList);
        return treeList;

    }

    @Override
    public Map<String, Object> sumData(Map params)throws Exception {
        Map<String, Object> dataMap=commonMapper.sumData();
        String filter=(String)params.get("filter");
        List<Map<String, Object>> reportNumByMonth=commonMapper.queryListBySql("SELECT \n" +
                "    REPLACE(DATE_FORMAT(report_code_create_time, '%m月'),'0','') AS month, COUNT(*) AS total FROM  puyu_t_report\n" +
                "GROUP BY  month ORDER BY  month");

        List<Map<String, Object>> sampleNumByMonth=commonMapper.queryListBySql("SELECT \n" +
                "    REPLACE(DATE_FORMAT(sample_code_create_time, '%m月'),'0','') AS month, COUNT(*) AS total FROM  puyu_t_sample\n" +
                "GROUP BY  month ORDER BY  month");
        dataMap.put("reportByMonth",reportNumByMonth);
        dataMap.put("sampleByMonth",sampleNumByMonth);
        return dataMap;
    }

    @Override
    public Map<String, Object> appRecordVideo(@NotNull Map params) throws Exception{
        log.error("appRecordVideo----->>接收到前台的传值是："+params.toString());
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
//        String sampleId =params.get("sampleId")+"";
//        String videoContent =params.get("videoContent")+"";
//        commonMapper.executeSql("update puyu_t_sample  set video_content='"+videoContent+"' where sample_id='"+sampleId+"'");
        //单条查询样品对应的设备信息
//        Map<String,Object> sample= sampleDao.queryById(sampleId);
        String deviceSerial =params.get("deviceSerial")+"";
        String localIndex =params.get("localIndex")==null?"1":params.get("localIndex")+"";
        Date date=dateFormat.parse(params.get("startTime")+"");
        date=DateUtil.offsetSecond(date,-30);
        String startTime =dateFormat.format(date);

        date=dateFormat.parse(params.get("endTime")+"");
        date=DateUtil.offsetSecond(date,-30);
        String endTime =dateFormat.format(date);
        //        if (StringUtils.isEmpty(startTime)||StringUtils.isEmpty(endTime)){
//            throw new BaseException(MessageUtils.message("H009"));
//        }
        if (StringUtils.isEmpty(deviceSerial)){
            throw new BaseException(MessageUtils.message("H010"));
        }
        //在缓存中读取上次存储的accessToken
        String accessToken= (String) redisUtil.get("accessToken");
        String taskId="";

        Map<String,String> headerMap=new HashMap<>();
        StringBuffer stringBuffer=new StringBuffer();
        String returnJson="";
        Map<String,Object> returnMap=new HashMap<>();
        if (StringUtils.isEmpty(accessToken)){
            //https://open.ys7.com/api/lapp/token/get请求得到accessToken
//            HttpUtil.post()
            stringBuffer.append("appKey=80ce9fc425cc484fab9fc56429d5734a");
            stringBuffer.append("&appSecret=cdf549f81ef4d3c926f168990b73aa25");
            returnJson=HttpClientUilt.sendHttpPostXWWW("https://open.ys7.com/api/lapp/token/get",stringBuffer.toString(),headerMap);
            returnMap= (Map<String, Object>)((Map<String, Object>) JSONObject.parse(returnJson)).get("data");
            accessToken=returnMap.get("accessToken")+"";
            //将得到的accessToken再次存储
            redisUtil.set("accessToken",accessToken,86400);//默认为1天
        }


        //https://open.ys7.com/api/open/cloud/v1/instant/record/save上传即时录制的视频
        stringBuffer=new StringBuffer();
        stringBuffer.append("projectId=rgzjsyxt");
        stringBuffer.append("&startTime=" + startTime);//录制时长
        stringBuffer.append("&endTime=" + endTime);//录制时长
        stringBuffer.append("&streamType=2");//视频为标清
        stringBuffer.append("&recType=local");//录像类型
        headerMap.put("accessToken",accessToken);
        headerMap.put("deviceSerial",deviceSerial);//设备序列号
        headerMap.put("localIndex",localIndex);//设备通道号（默认为1）
        String taskJson="";
        int i=0;
        while(ObjectUtil.isEmpty(returnMap)&&i<40) {
            Thread.sleep(1000);
            ++i;
            taskJson=HttpClientUilt.sendHttpPostXWWW("https://open.ys7.com/api/v3/open/cloud/open/cloud/v1/rec/video/save",stringBuffer.toString(),headerMap);
            returnMap= (Map<String, Object>)((Map<String, Object>) JSONObject.parse(taskJson)).get("data");
        }
        log.error("returnMap的值为===============："+returnMap);
        log.error("========获取大华视频等待"+i+"秒===========");
        log.error("============得到大华上传成功的视频json串为："+taskJson);
        returnMap.put("accessToken",accessToken);

        return returnMap;
    }

    @Override
    public Map<String, Object> uploadVideo(Map params)throws Exception {
        log.error("uploadVideo----->>接收到前台的传值是："+params.toString());
        String accessToken= (String) redisUtil.get("accessToken");
        String taskId=params.get("taskId")+"";
        String sampleId=params.get("sampleId")+"";
        String startTime =params.get("startTime")+"";
        String endTime =params.get("endTime")+"";
        Map<String,Object> returnMap=new HashMap<>();

        String fileUrl="";
        String returnJson="";
        List<Map<String, Object>> returnList=new ArrayList<>();
        //https://open.ys7.com/api/v3/open/cloud/task/files获得filedId
        int i=0;
       while(ObjectUtil.isEmpty(returnList)&&i<40){
           Thread.sleep(1000);//视频上传过慢，等待一段时间之后再查询视频详情
           ++i;
           returnJson=HttpClientUilt.sendHttpGet("https://open.ys7.com/api/v3/open/cloud/task/files?accessToken="+accessToken+"&taskId="+taskId,"");
           returnList= (List<Map<String, Object>>)((Map<String, Object>) JSONObject.parse(returnJson)).get("data");
       }
        log.error("returnList的值为===============："+returnList);
        log.error("========获取大华任务列表等等待"+i+"秒===========");
        String fileId=returnList.get(0).get("fileId")+"";


        //https://open.ys7.com/api/service/cloudrecord/file/official/download获取视频下载地址
        returnJson=HttpClientUilt.sendHttpGet("https://open.ys7.com/api/service/cloudrecord/file/official/download?fileId="+fileId+"&projectId=rgzjsyxt",accessToken);
        returnMap= (Map<String, Object>)((Map<String, Object>) JSONObject.parse(returnJson)).get("data");
        List<String> urls=((List<String>)returnMap.get("urls"));

        if (urls.size()>0)fileUrl=urls.get(0);

        //下载视频（可以不下载，萤石云直接设置不过期）
        MultipartFile video= null;
        try {
            video = CommonUtil.downloadFileAsMultipart(fileUrl.trim());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //上传视频到本地库（可以不上传，萤石云直接设置不过期）
        Map<String, Object> sample=new HashMap<>();
        //判空
        if (ObjectUtil.isNotEmpty(video)){
            //上传文件到Minio
            SysTFileUpload upload = sysTFileUploadService.upload(video);
            FileUploadVo vo = new FileUploadVo();
            vo.setId(sampleId);
            List<String> ids = new ArrayList<>();
            ids.add(upload.getFileId());
            vo.setFileIds(ids);
            //文件关联表
            sysTFileCenterService.saveByFile(vo);

            //视频地址
            sample.put("videoContent",params.get("videoContent"));
            sample.put("videoPath",upload.getFileUrl());
            sample.put("sampleId",sampleId);
            sample.put("videoStatus","2");
            sample.put("videoStartTime",startTime);
            sample.put("videoEndTime",endTime);

        }else {
            log.error("===============未获取到大华视频=====================");
        }

        //修改样品状态为生成状态。二维码地址和时间(视频状态、视频上传地址和开始结束时间)
        this.sampleDao.update(sample);
        return null;
    }

}
